package com.sunxd.vue.domain.service;

import com.alibaba.fastjson.JSON;
import com.sunxd.vue.bean.request.UserPageReq;
import com.sunxd.vue.bean.request.UserReq;
import com.sunxd.vue.bean.request.UserUpdateReq;
import com.sunxd.vue.domain.bean.assembler.UserAssembler;
import com.sunxd.vue.domain.bean.domain.User;
import com.sunxd.vue.domain.repository.UserRepository;
import com.sunxd.vue.infrastructure.adapter.db.base.Paging;
import com.sunxd.vue.infrastructure.adapter.db.mapping.UserMapping;
import com.sunxd.vue.infrastructure.adapter.db.po.UserPO;
import com.sunxd.vue.infrastructure.utils.BeanMapUtil;
import com.sunxd.vue.infrastructure.utils.PagingUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

/**
 * @author sun.xd
 * @description: description
 * @date 2024/4/2 10:56
 */
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;

    public boolean create(UserReq req) {
        return userRepository.save(UserAssembler.CONVERTER.req2do(req));
    }

    public boolean update(UserUpdateReq req) {
        return userRepository.update(UserAssembler.CONVERTER.upReq2do(req));
    }

    public Paging<User> page(UserPageReq req) {
        return userRepository.paging(PagingUtil.addPageParam(BeanMapUtil.beanToMap(req), req));
    }

    public User findByUserName(String name) {
        return userRepository.findByName(name);
    }

    public User findOne(User user) {
        return userRepository.findOne(user);
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean testTran(UserReq req) {
        userRepository.save(UserAssembler.CONVERTER.req2do(req));
        userRepository.save(UserAssembler.CONVERTER.req2do(req));
        Random random = new Random();
        if(random.nextInt(10)<=5){
            throw new RuntimeException("自定义异常");
        }
        return Boolean.TRUE;
    }


    public static void main(String[] args) {
        User user1 =  new User();
        user1.setId(1L);
        user1.setName("1name");

        User user2 =  new User();

        BeanUtils.copyProperties(user1,user2);
        System.out.println(1+ JSON.toJSONString(user1));
        System.out.println(2+ JSON.toJSONString(user2));

        user1.setId(2L);
        user1.setName("2name");

        System.out.println(3+ JSON.toJSONString(user1));
        System.out.println(4+ JSON.toJSONString(user2));

    }

}
